package ucadminlogic

import (
	"context"
	"github.com/zeromicro/go-zero/core/logx"
	"go.uber.org/zap"
	"navi-mumbai/app/rpc/usercenter/internal/svc"
	"navi-mumbai/app/rpc/usercenter/pb"
	"navi-mumbai/common/key/dbkey"
	"navi-mumbai/common/xerr"
	"time"
)

type QueryUserInviteOrderFlowLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewQueryUserInviteOrderFlowLogic(ctx context.Context, svcCtx *svc.ServiceContext) *QueryUserInviteOrderFlowLogic {
	return &QueryUserInviteOrderFlowLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

// 创建UserInviteOrderFlow设置
func (l *QueryUserInviteOrderFlowLogic) QueryUserInviteOrderFlow(in *pb.QueryUserInviteOrderFlowReq) (*pb.QueryUserInviteOrderFlowResp, error) {
	var start, end *time.Time
	if in.StartTime != "" {
		var t time.Time
		loc, _ := time.LoadLocation(dbkey.DateTimeZone)
		t, err := time.ParseInLocation(dbkey.DateTimeCNFormat, in.StartTime, loc)
		if err != nil {
			return nil, xerr.NewGrpcErrCodeMsg(xerr.RequestParamError, "invalid start time")
		}
		start = &t
	}
	if in.EndTime != "" {
		loc, _ := time.LoadLocation(dbkey.DateTimeZone)
		t, err := time.ParseInLocation(dbkey.DateTimeCNFormat, in.EndTime, loc)
		if err != nil {
			return nil, xerr.NewGrpcErrCodeMsg(xerr.RequestParamError, err.Error())
		}
		end = &t
	}
	l.Logger.Errorf("QueryUserInviteOrderFlow in :  ", in)
	resp, err := l.svcCtx.UserInviteOrderFlowModel.Find(l.ctx, in.Uid, in.RebateType, in.Type, in.MoneyAmount, start, end, in.PageNo, in.PageSize)
	if err != nil {
		l.Logger.Errorf("QueryUserInviteOrderFlowReq Find failed ", zap.Error(err))
		return nil, xerr.NewGrpcErrCodeMsg(xerr.DbError, err.Error())
	}
	r := &pb.QueryUserInviteOrderFlowResp{
		List: make([]*pb.UserInviteOrderFlowData, 0),
	}
	for _, d := range resp {
		queryData := &pb.UserInviteOrderFlowData{
			Id:          d.Id, // 序号
			Uid:         d.Pid,
			FromUid:     d.Uid,
			MoneyAmount: d.MoneyAmount,
			Type:        d.Type,
			RebateType:  d.RebateType,
			CreateTime:  d.CreateTime.Format(dbkey.DateTimeCNFormat),
			UpdateTime:  d.UpdateTime.Format(dbkey.DateTimeCNFormat),
		}
		r.List = append(r.List, queryData)
	}
	l.Logger.Errorf("QueryUserInviteOrderFlow r :  ", r)
	r.Total, err = l.svcCtx.UserInviteOrderFlowModel.Count(l.ctx, in.Uid, in.RebateType, in.Type, in.MoneyAmount, start, end)
	if err != nil {
		l.Logger.Errorf("QueryUserInviteOrderFlowReq Count failed ", zap.Error(err))
		return nil, xerr.NewGrpcErrCodeMsg(xerr.DbError, err.Error())
	}
	return r, nil
}
